package com.code.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.code.dao.MenuMapper;
import com.code.pojo.Menu;
import com.code.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    MenuMapper menuMapper;

    @Override
    public List<Map> getMenuInfo() {
        List<Menu> menus = menuMapper.selectAll();
        return findChildrenByPid(menus,"0");
    }

//    根据pid找子类
    public List<Map> findChildrenByPid(List<Menu> menus,String parentId){
        List<Map> list=new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId().equals(parentId)) {
                HashMap hashMap = new HashMap<>();
                hashMap.put("path",menu.getId());
                hashMap.put("title",menu.getName());
                hashMap.put("icon",menu.getIcon());
                hashMap.put("linkUrl",menu.getUrl());
//                递归的自调用查找
                List<Map> children = findChildrenByPid(menus, menu.getId());
                if (!CollectionUtils.isEmpty(children)) {
                    hashMap.put("children",children);
                }
                list.add(hashMap);
            }
        }
        return list;
    }
}
